package com.cx.common.utils;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.NonTypedScalarSerializerBase;

import java.io.IOException;
import java.lang.reflect.Type;
import java.text.DecimalFormat;

/**
*
* @Author:cxy
* @Date:2019/10/24 15:11
*/
public class DoubleSerializer extends NonTypedScalarSerializerBase<Double> {

	private static final DecimalFormat format = new DecimalFormat("##.####");

	public static final DoubleSerializer INSTANCE = new DoubleSerializer();

	private DoubleSerializer() {
		super(Double.class);
	}

	@Override
	public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider)
			throws IOException, JsonGenerationException {
		if (null == value) {
			jgen.writeNull();
		}
		else {
			jgen.writeNumber(format.format(value));
		}
	}

	@Override
	public JsonNode getSchema(SerializerProvider provider, Type typeHint) {
		return createSchemaNode("number", true);
	}
}
